package leetcode.day_2021_3_1_2022_3_7;

import java.util.*;

/**
 * 40. 组合总和 II
 * https://leetcode-cn.com/problems/combination-sum-ii/
 */
public class LeetCode0040 {

    static List<List<Integer>> res = new ArrayList<>();
    static Set<String> set = new HashSet<>();

    public static List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        solve(candidates, target, 0, 0, new ArrayList<>());
        return res;
    }

    public static void solve(int[] candidates, int target, int sum, int begin, List<Integer> list) {
        if (sum == target && !set.contains(list.toString())) {
            set.add(list.toString());
            res.add(new ArrayList<>(list));
            return;
        }

        for (int i=begin; i<candidates.length; i++) {
            if (target < candidates[i] || (sum + candidates[i]) > target) continue;
            list.add(candidates[i]);
            sum += candidates[i];
            solve(candidates, target, sum, i+1, list);
            sum -= candidates[i];
            list.remove(list.size()-1);
        }
    }

    public static void main(String[] args) {
        System.out.println(combinationSum2(new int[]{10,1,2,7,6,1,5}, 8));
    }
}
